﻿using System;
using K9Nano.Domain;
using K9Nano.MultiTenancy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.MySql
{
    public static class MySqlExtensions
    {
        public static IK9NanoAppBuilder AddMySqlEfCore<TDbContext>(this IK9NanoAppBuilder builder,
            MySqlOption option,
            string migrationsAssembly = null,
            Action<DbContextOptionsBuilder> dbSetupAction = null)
            where TDbContext : DbContext
        {
            builder.AddEfCore<TDbContext>(db =>
            {
                db.UseMySql(option, migrationsAssembly);

                dbSetupAction?.Invoke(db);
            });

            builder.Services.Configure<MySqlOption>(b => b.CloneFrom(option));

            builder.Services.AddSingleton<ITenantStore, MySqlTenantStore>();

            builder.Services.AddScoped<IReadOnlyDbConnectionFactory, MySqlReadOnlyDbConnectionFactory>();

            return builder;
        }

        public static DbContextOptionsBuilder UseMySql(this DbContextOptionsBuilder builder, MySqlOption option, string migrationsAssembly = null)
        {
            builder.UseMySql(option.ConnectionString,
                b =>
                {
                    b.ServerVersion(option.ServerVersion);
                    if (!string.IsNullOrEmpty(migrationsAssembly))
                    {
                        b.MigrationsAssembly(migrationsAssembly);
                    }
                });
            return builder;
        }
    }
}